package com.qihoo.finance.backup.reader;

import com.qihoo.finance.backup.BackMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.math.BigInteger;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MybatisBackIterator implements Iterator<List<Map<String, Object>>> {

    private IteratorBackConf conf;

    private SqlSession sqlSession;

    private BackMapper mapper;
    private boolean hasNext = true;

    public void setConf(IteratorBackConf conf) {
        this.conf = conf;
    }

    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addMapper(BackMapper.class);
        sqlSession = sqlSessionFactory.openSession();
        mapper = sqlSession.getMapper(BackMapper.class);
    }

    public void close() {
        if (sqlSession != null) {
            sqlSession.close();
            sqlSession = null;
        }
    }

    @Override
    public boolean hasNext() {
        return hasNext;
    }

    @Override
    public List<Map<String, Object>> next() {
        List<Map<String, Object>> read = mapper.read(conf);
        long aLong = read.stream().map(stringObjectMap -> ((BigInteger) stringObjectMap.get(conf.getKey())).longValue()).max(Long::compareTo).orElse(-1L);
        if (aLong == -1L) {
            hasNext = false;
            return Collections.emptyList();
        }
        conf.setMinKey(aLong + 1);
        return read;
    }
}
